import json
import math
import random
from subprocess import Popen, PIPE

from locust import task, HttpUser, between, LoadTestShape
from logger import logger


class TaskSet(HttpUser):
    wait_time = between(0.1, 0.3)

    # def login(self):
    #     pass

    def on_start(self):
        self.base_url = "https://people-survey.staging.shopee.com"
        self.headers = {
            "Content-Type": "application/json",
            "cookie": "PS-Survey=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjozOTEyNTM4OTY0NTE5MDY5OTksImV4cCI6MTY0MzE2NTM2OCwiaXNzIjoiUFMtU3VydmV5IiwibmJmIjoxNjQyOTkxNTY4fQ.V37l9cWo0FOZTPsRaA02pbTORFVN3MQurJOxOysNJDs"
        }

    # def read_txt(self, filename):
    #     # You can do this once in your program
    #     lines = open(filename, encoding='utf-8').read().splitlines()
    #
    #     # Whenever you need a new random line, you do this
    #     randomline = random.choice(lines)
    #     # return json.loads(randomline)
    #     return randomline

    @task(1)
    def task1(self):

        uri = "/survey/api/v1/web/questionnaire/previewSurvey"
        survey_id = random.choice(["391736543703742086", "391736765196547718", "391737334749465741"])

        data = {
            "survey_id": survey_id,
            "channel_type": 0
        }

        with self.client.post(url=self.base_url+uri, timeout=5,
                             name=uri,
                             catch_response=True,
                             headers=self.headers,
                             data=json.dumps(data)) as res:
            if res.status_code == 200 and res.json()["msg"] == "success":
                res.success()
            else:
                logger.info("task1 接口状态码:{},接口返回:{}".format(res.status_code, res.text))
                res.failure(
                    '请求失败,参数为:{},status_code={},rsp_body:{}'.format(uri, res.status_code, res.text))


class TimeShape(LoadTestShape):
    """
        duration -- 多少秒后进入下一个阶段
        users -- 用户数
        spawn_rate -- 每秒要启动/停止的用户数
    """

    stages = [
        {"duration": 300, "users": 100, "spawn_rate": 5},
        {"duration": 600, "users": 130, "spawn_rate": 5},
        {"duration": 900, "users": 160, "spawn_rate": 5},
        {"duration": 1200, "users": 180, "spawn_rate": 5},
        {"duration": 1500, "users": 200, "spawn_rate": 5},
        {"duration": 1800, "users": 220, "spawn_rate": 5},
        {"duration": 2100, "users": 240, "spawn_rate": 5},
        {"duration": 2400, "users": 260, "spawn_rate": 5},
        {"duration": 2700, "users": 280, "spawn_rate": 5},
        {"duration": 3000, "users": 300, "spawn_rate": 5},
        {"duration": 3300, "users": 320, "spawn_rate": 1},
        {"duration": 3600, "users": 330, "spawn_rate": 1},
        {"duration": 3900, "users": 340, "spawn_rate": 1},
        {"duration": 4200, "users": 350, "spawn_rate": 1},
        {"duration": 4500, "users": 360, "spawn_rate": 1},
        {"duration": 4800, "users": 370, "spawn_rate": 1},
        {"duration": 5100, "users": 380, "spawn_rate": 1},
        {"duration": 5400, "users": 390, "spawn_rate": 1},
        {"duration": 5700, "users": 400, "spawn_rate": 1},
    ]

    def tick(self):
        run_time = self.get_run_time()

        for stage in self.stages:
            if run_time < stage["duration"]:
                tick_data = (stage["users"], stage["spawn_rate"])
                return tick_data

        return None


if __name__ == "__main__":
    filename = __file__
    cmd = 'locust -f ' + filename
    # print(cmd,)
    import os
    os.popen(cmd).readlines()
    # p = Popen(cmd, stdout=PIPE, shell=True, stderr=PIPE)
    # p = Popen(cmd)
    # p.stdout.readlines()